package com.example.chao.myphotosearch.presenter;

import android.os.Handler;
import android.os.Message;

import com.example.chao.myphotosearch.view.IView;

import javax.inject.Inject;

/**
 * Created by chao on 2016/3/17.
 */
public class LaunchPresenter implements IPresenter<IView<String>>{
    private boolean isCounting = true;
    private CountingHandler countingHandler;
    private CountingRunnable countingRunnable;
    private final static int START = 0;
    private final static int COUNTING = 1;
    private final static int FINISH = 2;
    private int count = 3;
    private IView<String> iView;

    @Inject
    public LaunchPresenter(){
        countingHandler = new CountingHandler();
        countingRunnable = new CountingRunnable();
    }

    @Override
    public void onCreate(IView<String> iView) {
        this.iView = iView;
        countingHandler.obtainMessage(START).sendToTarget();
    }

    @Override
    public void onViewCreated() {
        iView.detachView();
        isCounting = false;
    }

    private class CountingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case START:
                    iView.attachView("跳过广告  " + count);
                    isCounting = true;
                    countingHandler.postDelayed(countingRunnable,1000);
                    break;
                case COUNTING:
                    iView.attachView("跳过广告  " + count);
                    countingHandler.postDelayed(countingRunnable,1000);
                    break;
                case FINISH:
//                    isCounting = false;
                    onViewCreated();
                    break;
            }
        }
    }
    private class CountingRunnable implements Runnable{

        @Override
        public void run() {
            if (isCounting) {
                if (--count> 0) {
                    countingHandler.obtainMessage(COUNTING).sendToTarget();
                } else {
                    countingHandler.obtainMessage(FINISH).sendToTarget();
                }
            }
        }
    }
}
